package com.ldc.commonlibs.ui;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.ldc.commonlibs.views.StateViewLayout;

/**
 * @author liudc
 * @since 2022/7/3 13:57
 */
public abstract class FragmentBase extends Fragment {
    private StateViewLayout stateViewLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = getLayoutView(inflater, container);
        stateViewLayout = initStateViewLayout();
        preMain(savedInstanceState);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            main(savedInstanceState);
        } catch (Exception error) {
            processError(error);
        }
    }

    protected View getLayoutView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return null;
    }

    /**
     * 主函数之前
     *
     * @param savedInstanceState 数据
     */
    protected void preMain(@Nullable Bundle savedInstanceState) {
    }

    /**
     * 主函数
     *
     * @param savedInstanceState 数据
     */
    protected abstract void main(@Nullable Bundle savedInstanceState);

    /**
     * 异常处理
     *
     * @param error 错误
     */
    protected void processError(Exception error) {
        error.printStackTrace();
    }

    /**
     * 状态视图
     *
     * @return 转态视图
     */
    protected StateViewLayout initStateViewLayout() {
        return null;
    }

    public StateViewLayout getStateViewLayout() {
        return stateViewLayout;
    }

    // 显示内容
    public void showContentView() {
        if (stateViewLayout != null) {
            stateViewLayout.showContentView();
        }
    }

    // 显示成功页面
    public void showSuccessView() {
        if (stateViewLayout != null) {
            stateViewLayout.showSuccessView();
        }
    }

    public void showEmptyView() {
        if (stateViewLayout != null) {
            stateViewLayout.showEmptyView();
        }
    }

    // 显示加载
    public void showLoadingView() {
        if (stateViewLayout != null) {
            stateViewLayout.showLoadingView();
        }
    }

    // 显示错误
    public void showErrorView() {
        if (stateViewLayout != null) {
            stateViewLayout.showErrorView();
        }
    }
}
